6878712d55f5a275018729c77231e23cbad8cb54
3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace Wikimedia\Rdbms
;
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\NullLogger
;
27 use Wikimedia\ScopedCallback
;
31 use MaintainableDBConnRef
;
39 use DBUnexpectedError
;
40 use DBTransactionError
;
41 use DBTransactionSizeError
;
42 use DBConnectionError
;
43 use InvalidArgumentException
;
48 * Database connection, tracking, load balancing, and transaction manager for a cluster
52 class LoadBalancer
implements ILoadBalancer
{
53 /** @var array[] Map of (server index => server config array) */
55 /** @var \Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
57 /** @var float[] Map of (server index => weight) */
59 /** @var array[] Map of (group => server index => weight) */
61 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
62 private $mAllowLagged;
63 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
64 private $mWaitTimeout;
65 /** @var array The LoadMonitor configuration */
66 private $loadMonitorConfig;
67 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
68 private $tableAliases = [];
70 /** @var ILoadMonitor */
76 /** @var WANObjectCache */
78 /** @var object|string Class name or object With profileIn/profileOut methods */
80 /** @var TransactionProfiler */
81 protected $trxProfiler;
82 /** @var LoggerInterface */
83 protected $replLogger;
84 /** @var LoggerInterface */
85 protected $connLogger;
86 /** @var LoggerInterface */
87 protected $queryLogger;
88 /** @var LoggerInterface */
89 protected $perfLogger;
91 /** @var \Database Database connection that caused a problem */
92 private $errorConnection;
93 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
95 /** @var bool|DBMasterPos False if not set */
97 /** @var bool Whether the generic reader fell back to a lagged replica DB */
98 private $laggedReplicaMode = false;
99 /** @var bool Whether the generic reader fell back to a lagged replica DB */
100 private $allReplicasDownMode = false;
101 /** @var string The last DB selection or connection error */
102 private $mLastError = 'Unknown error';
103 /** @var string|bool Reason the LB is read-only or false if not */
104 private $readOnlyReason = false;
105 /** @var integer Total connections opened */
106 private $connsOpened = 0;
107 /** @var string|bool String if a requested DBO_TRX transaction round is active */
108 private $trxRoundId = false;
109 /** @var array[] Map of (name => callable) */
110 private $trxRecurringCallbacks = [];
111 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
112 private $localDomain;
113 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
114 private $localDomainIdAlias;
115 /** @var string Current server name */
117 /** @var bool Whether this PHP instance is for a CLI script */
119 /** @var string Agent name for query profiling */
122 /** @var callable Exception logger */
123 private $errorLogger;
126 private $disabled = false;
128 /** @var integer Warn when this many connection are held */
129 const CONN_HELD_WARN_THRESHOLD
= 10;
131 /** @var integer Default 'max lag' when unspecified */
132 const MAX_LAG_DEFAULT
= 10;
133 /** @var integer Seconds to cache master server read-only status */
134 const TTL_CACHE_READONLY
= 5;
136 public function __construct( array $params ) {
137 if ( !isset( $params['servers'] ) ) {
138 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
140 $this->mServers
= $params['servers'];
142 $this->localDomain
= isset( $params['localDomain'] )
143 ? DatabaseDomain
::newFromId( $params['localDomain'] )
144 : DatabaseDomain
::newUnspecified();
145 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
146 // always true, gracefully handle the case when they fail to account for escaping.
147 if ( $this->localDomain
->getTablePrefix() != '' ) {
148 $this->localDomainIdAlias
=
149 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
151 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
154 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
156 $this->mReadIndex
= -1;
163 $this->mWaitForPos
= false;
164 $this->mAllowLagged
= false;
166 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
167 $this->readOnlyReason
= $params['readOnlyReason'];
170 if ( isset( $params['loadMonitor'] ) ) {
171 $this->loadMonitorConfig
= $params['loadMonitor'];
173 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
176 foreach ( $params['servers'] as $i => $server ) {
177 $this->mLoads
[$i] = $server['load'];
178 if ( isset( $server['groupLoads'] ) ) {
179 foreach ( $server['groupLoads'] as $group => $ratio ) {
180 if ( !isset( $this->mGroupLoads
[$group] ) ) {
181 $this->mGroupLoads
[$group] = [];
183 $this->mGroupLoads
[$group][$i] = $ratio;
188 if ( isset( $params['srvCache'] ) ) {
189 $this->srvCache
= $params['srvCache'];
191 $this->srvCache
= new EmptyBagOStuff();
193 if ( isset( $params['memCache'] ) ) {
194 $this->memCache
= $params['memCache'];
196 $this->memCache
= new EmptyBagOStuff();
198 if ( isset( $params['wanCache'] ) ) {
199 $this->wanCache
= $params['wanCache'];
201 $this->wanCache
= WANObjectCache
::newEmpty();
203 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
204 if ( isset( $params['trxProfiler'] ) ) {
205 $this->trxProfiler
= $params['trxProfiler'];
207 $this->trxProfiler
= new TransactionProfiler();
210 $this->errorLogger
= isset( $params['errorLogger'] )
211 ?
$params['errorLogger']
212 : function ( Exception
$e ) {
213 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
216 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
217 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
220 $this->host
= isset( $params['hostname'] )
221 ?
$params['hostname']
222 : ( gethostname() ?
: 'unknown' );
223 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
224 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
228 * Get a LoadMonitor instance
230 * @return ILoadMonitor
232 private function getLoadMonitor() {
233 if ( !isset( $this->loadMonitor
) ) {
235 'LoadMonitor' => LoadMonitor
::class,
236 'LoadMonitorNull' => LoadMonitorNull
::class,
237 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
240 $class = $this->loadMonitorConfig
['class'];
241 if ( isset( $compat[$class] ) ) {
242 $class = $compat[$class];
245 $this->loadMonitor
= new $class(
246 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
247 $this->loadMonitor
->setLogger( $this->replLogger
);
250 return $this->loadMonitor
;
254 * @param array $loads
255 * @param bool|string $domain Domain to get non-lagged for
256 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
257 * @return bool|int|string
259 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
260 $lags = $this->getLagTimes( $domain );
262 # Unset excessively lagged servers
263 foreach ( $lags as $i => $lag ) {
265 # How much lag this server nominally is allowed to have
266 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
267 ?
$this->mServers
[$i]['max lag']
268 : self
::MAX_LAG_DEFAULT
; // default
269 # Constrain that futher by $maxLag argument
270 $maxServerLag = min( $maxServerLag, $maxLag );
272 $host = $this->getServerName( $i );
273 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
274 $this->replLogger
->error(
275 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
277 } elseif ( $lag > $maxServerLag ) {
278 $this->replLogger
->warning(
279 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
280 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
287 # Find out if all the replica DBs with non-zero load are lagged
289 foreach ( $loads as $load ) {
293 # No appropriate DB servers except maybe the master and some replica DBs with zero load
294 # Do NOT use the master
295 # Instead, this function will return false, triggering read-only mode,
296 # and a lagged replica DB will be used instead.
300 if ( count( $loads ) == 0 ) {
304 # Return a random representative of the remainder
305 return ArrayUtils
::pickRandom( $loads );
308 public function getReaderIndex( $group = false, $domain = false ) {
309 if ( count( $this->mServers
) == 1 ) {
310 # Skip the load balancing if there's only one server
311 return $this->getWriterIndex();
312 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
313 # Shortcut if generic reader exists already
314 return $this->mReadIndex
;
317 # Find the relevant load array
318 if ( $group !== false ) {
319 if ( isset( $this->mGroupLoads
[$group] ) ) {
320 $nonErrorLoads = $this->mGroupLoads
[$group];
322 # No loads for this group, return false and the caller can use some other group
323 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
328 $nonErrorLoads = $this->mLoads
;
331 if ( !count( $nonErrorLoads ) ) {
332 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
335 # Scale the configured load ratios according to the dynamic load if supported
336 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
338 $laggedReplicaMode = false;
340 # No server found yet
342 # First try quickly looking through the available servers for a server that
344 $currentLoads = $nonErrorLoads;
345 while ( count( $currentLoads ) ) {
346 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
347 $i = ArrayUtils
::pickRandom( $currentLoads );
350 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
351 # ChronologyProtecter causes mWaitForPos to be set via sessions.
352 # This triggers doWait() after connect, so it's especially good to
353 # avoid lagged servers so as to avoid just blocking in that method.
354 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
355 # Aim for <= 1 second of waiting (being too picky can backfire)
356 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
358 if ( $i === false ) {
359 # Any server with less lag than it's 'max lag' param is preferable
360 $i = $this->getRandomNonLagged( $currentLoads, $domain );
362 if ( $i === false && count( $currentLoads ) != 0 ) {
363 # All replica DBs lagged. Switch to read-only mode
364 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
365 $i = ArrayUtils
::pickRandom( $currentLoads );
366 $laggedReplicaMode = true;
370 if ( $i === false ) {
371 # pickRandom() returned false
372 # This is permanent and means the configuration or the load monitor
373 # wants us to return false.
374 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
379 $serverName = $this->getServerName( $i );
380 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
382 $conn = $this->openConnection( $i, $domain );
384 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
385 unset( $nonErrorLoads[$i] );
386 unset( $currentLoads[$i] );
391 // Decrement reference counter, we are finished with this connection.
392 // It will be incremented for the caller later.
393 if ( $domain !== false ) {
394 $this->reuseConnection( $conn );
401 # If all servers were down, quit now
402 if ( !count( $nonErrorLoads ) ) {
403 $this->connLogger
->error( "All servers down" );
406 if ( $i !== false ) {
407 # Replica DB connection successful.
408 # Wait for the session master pos for a short time.
409 if ( $this->mWaitForPos
&& $i > 0 ) {
412 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
413 $this->mReadIndex
= $i;
414 # Record if the generic reader index is in "lagged replica DB" mode
415 if ( $laggedReplicaMode ) {
416 $this->laggedReplicaMode
= true;
419 $serverName = $this->getServerName( $i );
420 $this->connLogger
->debug(
421 __METHOD__
. ": using server $serverName for group '$group'" );
428 * @param DBMasterPos|false $pos
430 public function waitFor( $pos ) {
431 $this->mWaitForPos
= $pos;
432 $i = $this->mReadIndex
;
435 if ( !$this->doWait( $i ) ) {
436 $this->laggedReplicaMode
= true;
441 public function waitForOne( $pos, $timeout = null ) {
442 $this->mWaitForPos
= $pos;
444 $i = $this->mReadIndex
;
446 // Pick a generic replica DB if there isn't one yet
447 $readLoads = $this->mLoads
;
448 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
449 $readLoads = array_filter( $readLoads ); // with non-zero load
450 $i = ArrayUtils
::pickRandom( $readLoads );
454 $ok = $this->doWait( $i, true, $timeout );
456 $ok = true; // no applicable loads
462 public function waitForAll( $pos, $timeout = null ) {
463 $this->mWaitForPos
= $pos;
464 $serverCount = count( $this->mServers
);
467 for ( $i = 1; $i < $serverCount; $i++
) {
468 if ( $this->mLoads
[$i] > 0 ) {
469 $ok = $this->doWait( $i, true, $timeout ) && $ok;
478 * @return IDatabase|bool
480 public function getAnyOpenConnection( $i ) {
481 foreach ( $this->mConns
as $connsByServer ) {
482 if ( !empty( $connsByServer[$i] ) ) {
483 /** @var $serverConns IDatabase[] */
484 $serverConns = $connsByServer[$i];
486 return reset( $serverConns );
494 * Wait for a given replica DB to catch up to the master pos stored in $this
495 * @param int $index Server index
496 * @param bool $open Check the server even if a new connection has to be made
497 * @param int $timeout Max seconds to wait; default is mWaitTimeout
500 protected function doWait( $index, $open = false, $timeout = null ) {
501 $close = false; // close the connection afterwards
503 // Check if we already know that the DB has reached this point
504 $server = $this->getServerName( $index );
505 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
506 /** @var DBMasterPos $knownReachedPos */
507 $knownReachedPos = $this->srvCache
->get( $key );
509 $knownReachedPos instanceof DBMasterPos
&&
510 $knownReachedPos->hasReached( $this->mWaitForPos
)
512 $this->replLogger
->debug( __METHOD__
.
513 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
517 // Find a connection to wait on, creating one if needed and allowed
518 $conn = $this->getAnyOpenConnection( $index );
521 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
525 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
527 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
531 // Avoid connection spam in waitForAll() when connections
532 // are made just for the sake of doing this lag check.
537 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
538 $timeout = $timeout ?
: $this->mWaitTimeout
;
539 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
541 if ( $result == -1 ||
is_null( $result ) ) {
542 // Timed out waiting for replica DB, use master instead
543 $this->replLogger
->warning(
544 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
545 [ 'host' => $server ]
549 $this->replLogger
->info( __METHOD__
. ": Done" );
551 // Remember that the DB reached this point
552 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
556 $this->closeConnection( $conn );
563 * @see ILoadBalancer::getConnection()
566 * @param array $groups
567 * @param bool $domain
569 * @throws DBConnectionError
571 public function getConnection( $i, $groups = [], $domain = false ) {
572 if ( $i === null ||
$i === false ) {
573 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
574 ' with invalid server index' );
577 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
578 $domain = false; // local connection requested
581 $groups = ( $groups === false ||
$groups === [] )
582 ?
[ false ] // check one "group": the generic pool
585 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
586 $oldConnsOpened = $this->connsOpened
; // connections open now
588 if ( $i == self
::DB_MASTER
) {
589 $i = $this->getWriterIndex();
591 # Try to find an available server in any the query groups (in order)
592 foreach ( $groups as $group ) {
593 $groupIndex = $this->getReaderIndex( $group, $domain );
594 if ( $groupIndex !== false ) {
601 # Operation-based index
602 if ( $i == self
::DB_REPLICA
) {
603 $this->mLastError
= 'Unknown error'; // reset error string
604 # Try the general server pool if $groups are unavailable.
605 $i = ( $groups === [ false ] )
606 ?
false // don't bother with this if that is what was tried above
607 : $this->getReaderIndex( false, $domain );
608 # Couldn't find a working server in getReaderIndex()?
609 if ( $i === false ) {
610 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
611 // Throw an exception
612 $this->reportConnectionError();
613 return null; // not reached
617 # Now we have an explicit index into the servers array
618 $conn = $this->openConnection( $i, $domain );
620 // Throw an exception
621 $this->reportConnectionError();
622 return null; // not reached
625 # Profile any new connections that happen
626 if ( $this->connsOpened
> $oldConnsOpened ) {
627 $host = $conn->getServer();
628 $dbname = $conn->getDBname();
629 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
633 # Make master-requested DB handles inherit any read-only mode setting
634 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
640 public function reuseConnection( $conn ) {
641 $serverIndex = $conn->getLBInfo( 'serverIndex' );
642 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
643 if ( $serverIndex === null ||
$refCount === null ) {
645 * This can happen in code like:
646 * foreach ( $dbs as $db ) {
647 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
649 * $lb->reuseConnection( $conn );
651 * When a connection to the local DB is opened in this way, reuseConnection()
655 } elseif ( $conn instanceof DBConnRef
) {
656 // DBConnRef already handles calling reuseConnection() and only passes the live
657 // Database instance to this method. Any caller passing in a DBConnRef is broken.
658 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
659 ( new RuntimeException() )->getTraceAsString() );
664 if ( $this->disabled
) {
665 return; // DBConnRef handle probably survived longer than the LoadBalancer
668 $domain = $conn->getDomainID();
669 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
670 throw new InvalidArgumentException( __METHOD__
.
671 ": connection $serverIndex/$domain not found; it may have already been freed." );
672 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
673 throw new InvalidArgumentException( __METHOD__
.
674 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
676 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
677 if ( $refCount <= 0 ) {
678 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
679 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
680 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
681 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
683 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
685 $this->connLogger
->debug( __METHOD__
.
686 ": reference count for $serverIndex/$domain reduced to $refCount" );
690 public function getConnectionRef( $db, $groups = [], $domain = false ) {
691 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
693 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
696 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
697 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
699 return new DBConnRef( $this, [ $db, $groups, $domain ] );
702 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
703 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
705 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
709 * @see ILoadBalancer::openConnection()
712 * @param bool $domain
713 * @return bool|Database
714 * @throws DBAccessError
716 public function openConnection( $i, $domain = false ) {
717 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
718 $domain = false; // local connection requested
721 if ( $domain !== false ) {
722 $conn = $this->openForeignConnection( $i, $domain );
723 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
724 $conn = $this->mConns
['local'][$i][0];
726 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
727 throw new InvalidArgumentException( "No server with index '$i'." );
729 // Open a new connection
730 $server = $this->mServers
[$i];
731 $server['serverIndex'] = $i;
732 $conn = $this->reallyOpenConnection( $server, false );
733 $serverName = $this->getServerName( $i );
734 if ( $conn->isOpen() ) {
735 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
736 $this->mConns
['local'][$i][0] = $conn;
738 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
739 $this->errorConnection
= $conn;
744 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
745 // Connection was made but later unrecoverably lost for some reason.
746 // Do not return a handle that will just throw exceptions on use,
747 // but let the calling code (e.g. getReaderIndex) try another server.
748 // See DatabaseMyslBase::ping() for how this can happen.
749 $this->errorConnection
= $conn;
757 * Open a connection to a foreign DB, or return one if it is already open.
759 * Increments a reference count on the returned connection which locks the
760 * connection to the requested domain. This reference count can be
761 * decremented by calling reuseConnection().
763 * If a connection is open to the appropriate server already, but with the wrong
764 * database, it will be switched to the right database and returned, as long as
765 * it has been freed first with reuseConnection().
767 * On error, returns false, and the connection which caused the
768 * error will be available via $this->errorConnection.
770 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
772 * @param int $i Server index
773 * @param string $domain Domain ID to open
776 private function openForeignConnection( $i, $domain ) {
777 $domainInstance = DatabaseDomain
::newFromId( $domain );
778 $dbName = $domainInstance->getDatabase();
779 $prefix = $domainInstance->getTablePrefix();
781 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
782 // Reuse an already-used connection
783 $conn = $this->mConns
['foreignUsed'][$i][$domain];
784 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
785 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
786 // Reuse a free connection for the same domain
787 $conn = $this->mConns
['foreignFree'][$i][$domain];
788 unset( $this->mConns
['foreignFree'][$i][$domain] );
789 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
790 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
791 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
792 // Reuse a connection from another domain
793 $conn = reset( $this->mConns
['foreignFree'][$i] );
794 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
795 // The empty string as a DB name means "don't care".
796 // DatabaseMysqlBase::open() already handle this on connection.
797 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
798 $this->mLastError
= "Error selecting database '$dbName' on server " .
799 $conn->getServer() . " from client host {$this->host}";
800 $this->errorConnection
= $conn;
803 $conn->tablePrefix( $prefix );
804 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
805 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
806 $this->connLogger
->debug( __METHOD__
.
807 ": reusing free connection from $oldDomain for $domain" );
810 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
811 throw new InvalidArgumentException( "No server with index '$i'." );
813 // Open a new connection
814 $server = $this->mServers
[$i];
815 $server['serverIndex'] = $i;
816 $server['foreignPoolRefCount'] = 0;
817 $server['foreign'] = true;
818 $conn = $this->reallyOpenConnection( $server, $dbName );
819 if ( !$conn->isOpen() ) {
820 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
821 $this->errorConnection
= $conn;
824 $conn->tablePrefix( $prefix );
825 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
826 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
830 // Increment reference count
831 if ( $conn instanceof IDatabase
) {
832 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
833 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
840 * Test if the specified index represents an open connection
842 * @param int $index Server index
846 private function isOpen( $index ) {
847 if ( !is_integer( $index ) ) {
851 return (bool)$this->getAnyOpenConnection( $index );
855 * Really opens a connection. Uncached.
856 * Returns a Database object whether or not the connection was successful.
859 * @param array $server
860 * @param string|bool $dbNameOverride Use "" to not select any database
862 * @throws DBAccessError
863 * @throws InvalidArgumentException
865 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
866 if ( $this->disabled
) {
867 throw new DBAccessError();
870 if ( $dbNameOverride !== false ) {
871 $server['dbname'] = $dbNameOverride;
874 // Let the handle know what the cluster master is (e.g. "db1052")
875 $masterName = $this->getServerName( $this->getWriterIndex() );
876 $server['clusterMasterHost'] = $masterName;
878 // Log when many connection are made on requests
879 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
880 $this->perfLogger
->warning( __METHOD__
. ": " .
881 "{$this->connsOpened}+ connections made (master=$masterName)" );
884 $server['srvCache'] = $this->srvCache
;
885 // Set loggers and profilers
886 $server['connLogger'] = $this->connLogger
;
887 $server['queryLogger'] = $this->queryLogger
;
888 $server['errorLogger'] = $this->errorLogger
;
889 $server['profiler'] = $this->profiler
;
890 $server['trxProfiler'] = $this->trxProfiler
;
891 // Use the same agent and PHP mode for all DB handles
892 $server['cliMode'] = $this->cliMode
;
893 $server['agent'] = $this->agent
;
894 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
895 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
896 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
898 // Create a live connection object
900 $db = Database
::factory( $server['type'], $server );
901 } catch ( DBConnectionError
$e ) {
902 // FIXME: This is probably the ugliest thing I have ever done to
903 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
907 $db->setLBInfo( $server );
908 $db->setLazyMasterHandle(
909 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
911 $db->setTableAliases( $this->tableAliases
);
913 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
914 if ( $this->trxRoundId
!== false ) {
915 $this->applyTransactionRoundFlags( $db );
917 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
918 $db->setTransactionListener( $name, $callback );
926 * @throws DBConnectionError
928 private function reportConnectionError() {
929 $conn = $this->errorConnection
; // the connection which caused the error
931 'method' => __METHOD__
,
932 'last_error' => $this->mLastError
,
935 if ( $conn instanceof IDatabase
) {
936 $context['db_server'] = $conn->getServer();
937 $this->connLogger
->warning(
938 "Connection error: {last_error} ({db_server})",
942 // throws DBConnectionError
943 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
945 // No last connection, probably due to all servers being too busy
946 $this->connLogger
->error(
947 "LB failure with no last connection. Connection error: {last_error}",
951 // If all servers were busy, mLastError will contain something sensible
952 throw new DBConnectionError( null, $this->mLastError
);
956 public function getWriterIndex() {
960 public function haveIndex( $i ) {
961 return array_key_exists( $i, $this->mServers
);
964 public function isNonZeroLoad( $i ) {
965 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
968 public function getServerCount() {
969 return count( $this->mServers
);
972 public function getServerName( $i ) {
973 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
974 $name = $this->mServers
[$i]['hostName'];
975 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
976 $name = $this->mServers
[$i]['host'];
981 return ( $name != '' ) ?
$name : 'localhost';
984 public function getServerInfo( $i ) {
985 if ( isset( $this->mServers
[$i] ) ) {
986 return $this->mServers
[$i];
992 public function setServerInfo( $i, array $serverInfo ) {
993 $this->mServers
[$i] = $serverInfo;
996 public function getMasterPos() {
997 # If this entire request was served from a replica DB without opening a connection to the
998 # master (however unlikely that may be), then we can fetch the position from the replica DB.
999 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1000 if ( !$masterConn ) {
1001 $serverCount = count( $this->mServers
);
1002 for ( $i = 1; $i < $serverCount; $i++
) {
1003 $conn = $this->getAnyOpenConnection( $i );
1005 return $conn->getReplicaPos();
1009 return $masterConn->getMasterPos();
1015 public function disable() {
1017 $this->disabled
= true;
1020 public function closeAll() {
1021 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1022 $host = $conn->getServer();
1023 $this->connLogger
->debug( "Closing connection to database '$host'." );
1029 'foreignFree' => [],
1030 'foreignUsed' => [],
1032 $this->connsOpened
= 0;
1035 public function closeConnection( IDatabase
$conn ) {
1036 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1037 foreach ( $this->mConns
as $type => $connsByServer ) {
1038 if ( !isset( $connsByServer[$serverIndex] ) ) {
1042 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1043 if ( $conn === $trackedConn ) {
1044 $host = $this->getServerName( $i );
1045 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1046 unset( $this->mConns
[$type][$serverIndex][$i] );
1047 --$this->connsOpened
;
1056 public function commitAll( $fname = __METHOD__
) {
1059 $restore = ( $this->trxRoundId
!== false );
1060 $this->trxRoundId
= false;
1061 $this->forEachOpenConnection(
1062 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1064 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1065 } catch ( DBError
$e ) {
1066 call_user_func( $this->errorLogger
, $e );
1067 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1069 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1070 $this->undoTransactionRoundFlags( $conn );
1076 throw new DBExpectedError(
1078 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1083 public function finalizeMasterChanges() {
1084 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1085 // Any error should cause all DB transactions to be rolled back together
1086 $conn->setTrxEndCallbackSuppression( false );
1087 $conn->runOnTransactionPreCommitCallbacks();
1088 // Defer post-commit callbacks until COMMIT finishes for all DBs
1089 $conn->setTrxEndCallbackSuppression( true );
1093 public function approveMasterChanges( array $options ) {
1094 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1095 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1096 // If atomic sections or explicit transactions are still open, some caller must have
1097 // caught an exception but failed to properly rollback any changes. Detect that and
1098 // throw and error (causing rollback).
1099 if ( $conn->explicitTrxActive() ) {
1100 throw new DBTransactionError(
1102 "Explicit transaction still active. A caller may have caught an error."
1105 // Assert that the time to replicate the transaction will be sane.
1106 // If this fails, then all DB transactions will be rollback back together.
1107 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1108 if ( $limit > 0 && $time > $limit ) {
1109 throw new DBTransactionSizeError(
1111 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1115 // If a connection sits idle while slow queries execute on another, that connection
1116 // may end up dropped before the commit round is reached. Ping servers to detect this.
1117 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1118 throw new DBTransactionError(
1120 "A connection to the {$conn->getDBname()} database was lost before commit."
1126 public function beginMasterChanges( $fname = __METHOD__
) {
1127 if ( $this->trxRoundId
!== false ) {
1128 throw new DBTransactionError(
1130 "$fname: Transaction round '{$this->trxRoundId}' already started."
1133 $this->trxRoundId
= $fname;
1136 $this->forEachOpenMasterConnection(
1137 function ( Database
$conn ) use ( $fname, &$failures ) {
1138 $conn->setTrxEndCallbackSuppression( true );
1140 $conn->flushSnapshot( $fname );
1141 } catch ( DBError
$e ) {
1142 call_user_func( $this->errorLogger
, $e );
1143 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1145 $conn->setTrxEndCallbackSuppression( false );
1146 $this->applyTransactionRoundFlags( $conn );
1151 throw new DBExpectedError(
1153 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1158 public function commitMasterChanges( $fname = __METHOD__
) {
1161 /** @noinspection PhpUnusedLocalVariableInspection */
1162 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1164 $restore = ( $this->trxRoundId
!== false );
1165 $this->trxRoundId
= false;
1166 $this->forEachOpenMasterConnection(
1167 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1169 if ( $conn->writesOrCallbacksPending() ) {
1170 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1171 } elseif ( $restore ) {
1172 $conn->flushSnapshot( $fname );
1174 } catch ( DBError
$e ) {
1175 call_user_func( $this->errorLogger
, $e );
1176 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1179 $this->undoTransactionRoundFlags( $conn );
1185 throw new DBExpectedError(
1187 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1192 public function runMasterPostTrxCallbacks( $type ) {
1193 $e = null; // first exception
1194 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1195 $conn->setTrxEndCallbackSuppression( false );
1196 if ( $conn->writesOrCallbacksPending() ) {
1197 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1198 // (which finished its callbacks already). Warn and recover in this case. Let the
1199 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1200 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1202 } elseif ( $conn->trxLevel() ) {
1203 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1204 // thus leaving an implicit read-only transaction open at this point. It
1205 // also happens if onTransactionIdle() callbacks leave implicit transactions
1206 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1207 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1211 $conn->runOnTransactionIdleCallbacks( $type );
1212 } catch ( Exception
$ex ) {
1216 $conn->runTransactionListenerCallbacks( $type );
1217 } catch ( Exception
$ex ) {
1225 public function rollbackMasterChanges( $fname = __METHOD__
) {
1226 $restore = ( $this->trxRoundId
!== false );
1227 $this->trxRoundId
= false;
1228 $this->forEachOpenMasterConnection(
1229 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1230 if ( $conn->writesOrCallbacksPending() ) {
1231 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1234 $this->undoTransactionRoundFlags( $conn );
1240 public function suppressTransactionEndCallbacks() {
1241 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1242 $conn->setTrxEndCallbackSuppression( true );
1247 * @param IDatabase $conn
1249 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1250 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1251 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1252 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1253 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1254 // If config has explicitly requested DBO_TRX be either on or off by not
1255 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1256 // for things like blob stores (ExternalStore) which want auto-commit mode.
1261 * @param IDatabase $conn
1263 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1264 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1265 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1269 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1270 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1271 $conn->flushSnapshot( __METHOD__
);
1275 public function hasMasterConnection() {
1276 return $this->isOpen( $this->getWriterIndex() );
1279 public function hasMasterChanges() {
1281 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1282 $pending |
= $conn->writesOrCallbacksPending();
1285 return (bool)$pending;
1288 public function lastMasterChangeTimestamp() {
1290 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1291 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1297 public function hasOrMadeRecentMasterChanges( $age = null ) {
1298 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1300 return ( $this->hasMasterChanges()
1301 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1304 public function pendingMasterChangeCallers() {
1306 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1307 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1313 public function getLaggedReplicaMode( $domain = false ) {
1314 // No-op if there is only one DB (also avoids recursion)
1315 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1317 // See if laggedReplicaMode gets set
1318 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1319 $this->reuseConnection( $conn );
1320 } catch ( DBConnectionError
$e ) {
1321 // Avoid expensive re-connect attempts and failures
1322 $this->allReplicasDownMode
= true;
1323 $this->laggedReplicaMode
= true;
1327 return $this->laggedReplicaMode
;
1331 * @param bool $domain
1333 * @deprecated 1.28; use getLaggedReplicaMode()
1335 public function getLaggedSlaveMode( $domain = false ) {
1336 return $this->getLaggedReplicaMode( $domain );
1339 public function laggedReplicaUsed() {
1340 return $this->laggedReplicaMode
;
1346 * @deprecated Since 1.28; use laggedReplicaUsed()
1348 public function laggedSlaveUsed() {
1349 return $this->laggedReplicaUsed();
1352 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1353 if ( $this->readOnlyReason
!== false ) {
1354 return $this->readOnlyReason
;
1355 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1356 if ( $this->allReplicasDownMode
) {
1357 return 'The database has been automatically locked ' .
1358 'until the replica database servers become available';
1360 return 'The database has been automatically locked ' .
1361 'while the replica database servers catch up to the master.';
1363 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1364 return 'The database master is running in read-only mode.';
1371 * @param string $domain Domain ID, or false for the current domain
1372 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1375 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1376 $cache = $this->wanCache
;
1377 $masterServer = $this->getServerName( $this->getWriterIndex() );
1379 return (bool)$cache->getWithSetCallback(
1380 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1381 self
::TTL_CACHE_READONLY
,
1382 function () use ( $domain, $conn ) {
1383 $old = $this->trxProfiler
->setSilenced( true );
1385 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1386 $readOnly = (int)$dbw->serverIsReadOnly();
1388 $this->reuseConnection( $dbw );
1390 } catch ( DBError
$e ) {
1393 $this->trxProfiler
->setSilenced( $old );
1396 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1400 public function allowLagged( $mode = null ) {
1401 if ( $mode === null ) {
1402 return $this->mAllowLagged
;
1404 $this->mAllowLagged
= $mode;
1406 return $this->mAllowLagged
;
1409 public function pingAll() {
1411 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1412 if ( !$conn->ping() ) {
1420 public function forEachOpenConnection( $callback, array $params = [] ) {
1421 foreach ( $this->mConns
as $connsByServer ) {
1422 foreach ( $connsByServer as $serverConns ) {
1423 foreach ( $serverConns as $conn ) {
1424 $mergedParams = array_merge( [ $conn ], $params );
1425 call_user_func_array( $callback, $mergedParams );
1431 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1432 $masterIndex = $this->getWriterIndex();
1433 foreach ( $this->mConns
as $connsByServer ) {
1434 if ( isset( $connsByServer[$masterIndex] ) ) {
1435 /** @var IDatabase $conn */
1436 foreach ( $connsByServer[$masterIndex] as $conn ) {
1437 $mergedParams = array_merge( [ $conn ], $params );
1438 call_user_func_array( $callback, $mergedParams );
1444 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1445 foreach ( $this->mConns
as $connsByServer ) {
1446 foreach ( $connsByServer as $i => $serverConns ) {
1447 if ( $i === $this->getWriterIndex() ) {
1448 continue; // skip master
1450 foreach ( $serverConns as $conn ) {
1451 $mergedParams = array_merge( [ $conn ], $params );
1452 call_user_func_array( $callback, $mergedParams );
1458 public function getMaxLag( $domain = false ) {
1463 if ( $this->getServerCount() <= 1 ) {
1464 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1467 $lagTimes = $this->getLagTimes( $domain );
1468 foreach ( $lagTimes as $i => $lag ) {
1469 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1471 $host = $this->mServers
[$i]['host'];
1476 return [ $host, $maxLag, $maxIndex ];
1479 public function getLagTimes( $domain = false ) {
1480 if ( $this->getServerCount() <= 1 ) {
1481 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1484 $knownLagTimes = []; // map of (server index => 0 seconds)
1485 $indexesWithLag = [];
1486 foreach ( $this->mServers
as $i => $server ) {
1487 if ( empty( $server['is static'] ) ) {
1488 $indexesWithLag[] = $i; // DB server might have replication lag
1490 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1494 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1497 public function safeGetLag( IDatabase
$conn ) {
1498 if ( $this->getServerCount() <= 1 ) {
1501 return $conn->getLag();
1506 * @param IDatabase $conn
1507 * @param DBMasterPos|bool $pos
1508 * @param int $timeout
1511 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1512 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1513 return true; // server is not a replica DB
1517 // Get the current master position, opening a connection if needed
1518 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1519 if ( $masterConn ) {
1520 $pos = $masterConn->getMasterPos();
1522 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1523 $pos = $masterConn->getMasterPos();
1524 $this->closeConnection( $masterConn );
1528 if ( $pos instanceof DBMasterPos
) {
1529 $result = $conn->masterPosWait( $pos, $timeout );
1530 if ( $result == -1 ||
is_null( $result ) ) {
1531 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1532 $this->replLogger
->warning( "$msg" );
1535 $this->replLogger
->info( __METHOD__
. ": Done" );
1539 $ok = false; // something is misconfigured
1540 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1546 public function setTransactionListener( $name, callable
$callback = null ) {
1548 $this->trxRecurringCallbacks
[$name] = $callback;
1550 unset( $this->trxRecurringCallbacks
[$name] );
1552 $this->forEachOpenMasterConnection(
1553 function ( IDatabase
$conn ) use ( $name, $callback ) {
1554 $conn->setTransactionListener( $name, $callback );
1559 public function setTableAliases( array $aliases ) {
1560 $this->tableAliases
= $aliases;
1563 public function setDomainPrefix( $prefix ) {
1564 if ( $this->mConns
['foreignUsed'] ) {
1565 // Do not switch connections to explicit foreign domains unless marked as free
1567 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1568 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1570 $domains = implode( ', ', $domains );
1571 throw new DBUnexpectedError( null,
1572 "Foreign domain connections are still in use ($domains)." );
1575 $this->localDomain
= new DatabaseDomain(
1576 $this->localDomain
->getDatabase(),
1581 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1582 $db->tablePrefix( $prefix );
1587 * Make PHP ignore user aborts/disconnects until the returned
1588 * value leaves scope. This returns null and does nothing in CLI mode.
1590 * @return ScopedCallback|null
1592 final protected function getScopedPHPBehaviorForCommit() {
1593 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1594 $old = ignore_user_abort( true ); // avoid half-finished operations
1595 return new ScopedCallback( function () use ( $old ) {
1596 ignore_user_abort( $old );
1603 function __destruct() {
1604 // Avoid connection leaks for sanity
1609 class_alias( LoadBalancer
::class, 'LoadBalancer' );